package com.yangtzeu.jwc.dao.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.yangtzeu.jwc.businessservice.BusinessHttpCallBack;
import com.yangtzeu.jwc.dao.JwcDao;
import com.yangtzeu.jwc.domain.KbSelection;
import com.yangtzeu.jwc.domain.News;
import com.yangtzeu.jwc.utils.ACache;
import com.yangtzeu.jwc.utils.G;
import com.zjsx.lib.utils.L;

/**
 * 有关教务处的操作,不需要登录
 *
 * @author ZhangDI
 */
public class JwcDaoImpl extends BasicDaoImpl implements JwcDao {
    private static JwcDao jwcDaoImpl;

    private JwcDaoImpl() {
        super();
    }

    ;

    public static JwcDao getInstance() {
        if (jwcDaoImpl == null) {
            jwcDaoImpl = new JwcDaoImpl();
        }
        return jwcDaoImpl;
    }

    public String getContentHtmlFromDoc(Document doc) {
        String html = doc.html();
        Element oe = doc.select("#contents").get(0);
        
        // 去掉所有background属性
        Elements bkcs = oe.getElementsByAttribute("background-color");
        for (int i = 0; i < bkcs.size(); i++) {
            bkcs.get(i).removeAttr("background-color");
        }
        bkcs = null;

        Elements ps = oe.select("p");
        Element p = null;
        // 去掉p的所有属性
        for (int i = 0; i < ps.size(); i++) {
            p = ps.get(i);
            removeAttr(p);
        }
        ps = null;
        p = null;
        // 去掉table的所有属性
        Elements tables = oe.select("table");
        Element table = null;
        Elements trs = null;
        Element tr = null;
        Elements tds = null;
        Element td = null;
        for (int i = 0; i < tables.size(); i++) {
            table = tables.get(i);
            removeAttr(table);
            table.attr("style", "border-collapse:collapse;border-spacing:0;border-left:1px solid #888;border-top:1px solid #888;background:#efefef;");
            trs = table.select("tr");
            for (int j = 0; j < trs.size(); j++) {
                tr = trs.get(j);
                removeAttr(tr);
                tds = tr.select("td");
                td = null;
                for (int k = 1; k < tds.size(); k++) {
                    td = tds.get(k);
                    clearTd(td);
                }
            }
        }
        Elements tds2 = oe.select("td");
        for(int i = 0 ; i < tds2.size() ; i++){
            clearTd(tds2.get(i));
            tds2.get(i).attr("style","border-right:1px solid #888;border-bottom:1px solid #888;");
        }
        Elements sps2 = oe.select("span");
        for(int i = 0 ; i<sps2.size() ;i++){
            removeAttr(sps2.get(i));
        }
        html = oe.html();
        html = html.replaceAll("<span>", "");
        html = html.replaceAll("</span>", "");
        L.e(html);
        return html;
    }
    
    public void clearTd(Element td){
	 // 记住该格子占用几行
        String rowspan = td.attr("rowSpan");
        String colspan = td.attr("colspan");
        removeAttr(td);
        L.d("td : " + td.html());
        if (!"".equals(rowspan) && rowspan != null)
            td.attr("rowspan", rowspan);
        if (!"".equals(colspan) && colspan != null)
            td.attr("colspan", colspan);
        td.attr("style", "border:1px solid black");
        Elements spans = td.select("span");
        Element span = null;
        for (int l = 0; l < spans.size(); l++) {
            span = spans.get(l);
            removeAttr(span);
        }
        Elements tdds = td.select("td");
    }


    /*
     * (non-Javadoc)
     *
     * @see com.zhangdi.dao.impl.JwcDao#getContentHtml(java.lang.String)
     */
    @Override
    public void getContentHtml(String path, final BusinessHttpCallBack callBack) {
        final String cacheName = path;
        final ACache aCache = ACache.get(app);
        final String docstr = aCache.getAsString(cacheName);
        if (docstr != null) {
            String html = getContentHtmlFromDoc(Jsoup.parse(docstr));
            callBack.onSuccess(null, null, false, html);
            return;
        }
        doHttpRequest(path, new BusinessHttpCallBack() {

            @Override
            public void onProgress(int bytesWritten, int totalSize) {
                callBack.onProgress(bytesWritten, totalSize);
            }

            @Override
            public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
                callBack.onFailure(responseBody, failuremsg, isNoticeDialog);
            }

            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
                try {
                    String html = getContentHtmlFromDoc((Document) obj);
                    callBack.onSuccess(responseBody, successMsg, isNoticeDialog, html);
                    aCache.put(cacheName, obj.toString(), ACache.TIME_MONTH);
                } catch (Exception e) {
                    callBack.onFailure(responseBody, "教务处服务器异常！", false);
                }
            }

        });
    }

    /*
     * (non-Javadoc)
     *
     * @see com.zhangdi.dao.impl.JwcDao#removeAttr(org.jsoup.nodes.Element)
     */
    @Override
    public void removeAttr(Element e) {
        if (e != null) {
            Attributes attrs = e.attributes();
            if (attrs != null) {
                for (Attribute attr : attrs.asList()) {
                    e.removeAttr(attr.getKey());
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see com.zhangdi.dao.impl.JwcDao#getIndex()
     */
    @Override
    public void getIndex(final BusinessHttpCallBack callBack) {
        String url = G.JWC_HOME;
        final String cacheName = url + (paramsMap == null ? "" : paramsMap.toString());
        final ACache aCache = ACache.get(app);
        final String docstr = aCache.getAsString(cacheName);
        if (docstr != null) {
            List<News> newss = getIndexFromDoc(Jsoup.parse(docstr));
            callBack.onSuccess(null, null, false, newss);
        }
        doHttpRequest(url, new BusinessHttpCallBack() {

            @Override
            public void onProgress(int bytesWritten, int totalSize) {
                callBack.onProgress(bytesWritten, totalSize);
            }

            @Override
            public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
                callBack.onFailure(responseBody, failuremsg, isNoticeDialog);
            }

            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
                try {
                    List<News> newss = getIndexFromDoc((Document) obj);
                    callBack.onSuccess(responseBody, null, false, newss);
                    aCache.put(cacheName, obj.toString());
                } catch (Exception e) {
                    callBack.onFailure(responseBody, "教务处服务器异常！", false);
                }
            }

        });
    }


    public List<News> getIndexFromDoc(Document doc) {
        List<News> newss = new ArrayList<News>();
        Element body = doc.body();
        String html = body.toString();

        Element e1 = body.select("img[useMap = #Map3]").get(0);
        Element e2 = body.select("img[useMap = #Map4]").get(0);
        Element e3 = body.select("img[useMap = #Mapgj]").get(0);

        String tzgg = html.substring(html.indexOf(e1.toString()),
                html.indexOf(e2.toString()));
        String jxdt = html.substring(html.indexOf(e2.toString()),
                html.indexOf(e3.toString()));

        Element tzgg_e = Jsoup.parse(tzgg);
        Element jxdt_e = Jsoup.parse(jxdt);

        Elements tzgg_content = tzgg_e.select(".title-content");
        Elements jxdt_content = jxdt_e.select(".title-content");

        // 通知公告
        Element e = null;
        String type = null;
        String time = null;
        String path = null;
        String biaoti = null;

        for (int i = 0; i < tzgg_content.size(); i++) {
            e = tzgg_content.get(i);
            type = "通知公告";
            time = e.select("td").get(2).text();
            path = G.JWC_HOME + "/"
                    + e.select("a").get(0).attr("href");
            biaoti = e.text();
            newss.add(new News(type,
                    biaoti.substring(0, biaoti.length() - 9), time, path,
                    null));
        }

        for (int i = 0; i < jxdt_content.size(); i++) {
            e = jxdt_content.get(i);
            type = "教学动态";
            time = e.select("td").get(2).text();
            path = G.JWC_HOME + "/"
                    + e.select("a").get(0).attr("href");
            biaoti = e.text();
            newss.add(new News(type,
                    biaoti.substring(0, biaoti.length() - 9), time, path,
                    null));
        }
        return newss;
    }
}
